package com.woniu.common;

import com.woniu.enumeration.BusinessCode;
import com.woniu.enumeration.ResultCode;
import com.woniu.exception.BookBusinessException;
import com.woniu.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class UserPrivilegeInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 重写前置通知,判断用户携带token是否合法
     * 1. 判断是否是options请求，如果是则直接放行
     * 2. 获取请求头
     * 3. 判断token是否存在
     * 4. 验证token是否有效
     * 5. 判断IP地址是否相同
     * 6. 如果都通过则放行
     * */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        // 1. 判断是否是options请求，如果是则直接放行
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        // 2. 获取请求头
        String token = request.getHeader("Authorization");
        // 3. 判断token是否存在
        if (token == null) {
            throw new BookBusinessException(BusinessCode.TOKEN_NOT_EXISTS);
        }

        // 处理token 前面的 "Bearer "这7个字符
        token = jwtUtils.getToken(token);
        // 设置 request的请求头 为token
        request.setAttribute("Authorization", token);

        // 4. 验证token是否有效
        if (!jwtUtils.validateToken(token)) {
            throw new BookBusinessException(BusinessCode.INVALID_TOKEN);
        }
        // 5. 判断IP地址是否相同,回去登录保存ip到token
//        String ip = jwtUtils.getValue(token, "ip");
//        String remoteAddr = request.getRemoteAddr();
//        if (!ip.equals(remoteAddr)) {
//            throw new BookBusinessException(BusinessCode.INVALID_IP);
//        }
        return true;
    }


}
